//初始化加载折线图和表格
$(document).ready(function () {
	siteKey = $("#siteKey").val();
	type = $("#hdtype").val();
	if(siteKey==""|| type ==""){
		var str = "<div class='em100 whitediv' id='zhanwushuju'><div class='em25'></div><div class='backyellow'>&nbsp;&nbsp;暂无数据！请选择场所</div></div>"
		$("#myForm .widthall .chartdiv").children("div[id!='zhanwushuju']").hide();
		$("#myForm .widthall .xiangxidiv").children("div[id!='zhanwushuju']").hide();
		$("#myForm .widthall .chartdiv").html(str);
		$("#myForm .widthall .xiangxidiv").html(str);
		
	}else{
		getIndexOrder();
	}
	
})

//时间段时间控件
$( function () {
	var endDate=new Date();//当前时间
	endDate=endDate.getFullYear()+"-"+(endDate.getMonth()+1)+"-"+endDate.getDate();
	var startDate=(new Date());
	startDate.setDate(startDate.getDate()-7);//前一周时间
	
	startDate=startDate.getFullYear()+"-"+(startDate.getMonth()+1)+"-"+startDate.getDate();

	siteKey = $("siteKey").val();
 	if(siteKey!=""){
	    var dateObj = {
	        theme: 'ta', // 日期选择器TA主题
	        autoCommit: true, //自动提交，完成日期初始化，以及图表的展示拉取
	        isTodayValid: true,
	        startDate: startDate,
	        endDate: endDate,
	        needCompare: true,
	        startCompareDate: '',
	        endCompareDate: '',
	        singleCompare: false,
	        defaultText: ' 至 ',
	        autoSubmit: false,
	        shortOpr: false,
	        target: 'datePicker',
	        calendars: 2,
	        inputTrigger: 'input_trigger',
	        compareCheckboxId: false,
	        success: function (obj) {
	            if (($("#txtspan").val().split("_"))[1] == "0" || $("#needCompare").val() == "1")//处于如期选择框时
	            {
	                loadChart($("#hdtype").val());
	            }
	        }
	    };
	    new pickerDateRange("date", dateObj)
 	}
})

function loadPaiHang(siteId, type) {}
//加载折线图表取XY轴
function  getXY(param,type) {
	var dataRe="";
	var datetime = new Array();
	var resultData = param.resultList;
	var indexName = getOrderField(type);
	for(var i=0;i<resultData.length;i++){
		dataRe=dataRe + getObjectVlue(resultData[i],indexName)+",";
		datetime.push(resultData[i].datatime);
		}
	dataRe=dataRe.substring(0,dataRe.length-1);
	var result =new Array();
	result.push(dataRe);
	result.push(datetime);
	return result
}

//开始时间
var stadubiao = "";
//结束时间
var endtubiao = "";
//导航
var siteN = "";
//指标单位
var zhibiaodanwei = "";
//指标名称
var indexname = "";
//场所名称
var siteName = "";

var siteTypeName ="";
//加载折线图表
 function loadChart(type) {
	 showLoading();
	 zhibiaoCss(type);
	 //获取指标名称
     indexname = array[parseInt(type)];
     //获取指标单位
	 zhibiaodanwei = arraydanwei[parseInt(type)];
     var data = [];
     var xsis = [];
     var from = $('#startDate').val();
     var to = $('#endDate').val();
     var siteId= $("#siteKey").val();
     var tubiao = "tubiao1";
     var span = $("#txtspan").val();
     shijianCss(span);
     var myChart = echarts.init(document.getElementById(tubiao));
   	$.ajax( {
   		type : "GET",
   		contentType:"application/json",
   		dataType : 'json',
   		url: "squareWeekGraph",
   		data: { from: from, to: to,type: type, span: span, siteId: siteId },
   		async: true,
   		success : function(ret) {  
   			var width = $("#tubiao1").width();
			var height = $("#tubiao1").height();
			var titleOffens = width*7.6/100;
			var dataZoomY = height*(1-19/100);
			var toolboxX = width*80/100;
			var legendY = height*4/100;
			var toolboxY = height*4/100;
			//获取当前时间
			var date = new Date;
			var today = timeFormat(date);
			//保存图片的名称
			var toolboxName = $("#titles").val()+'-星期走势'+today;
			siteName = ret.siteName
			siteN=ret.siteN;
			siteTypeName = ret.siteTypeName;
			stadubiao=ret.stadubiao;
			endtubiao=ret.endtubiao;
			titContext="数据说明："+siteTypeName+"指标星期走势"+"\n"
					+"时间范围："+stadubiao+(endtubiao==null?'':"~"+endtubiao)+"\n"
					+"场所名称："+siteN+"\n"
					+"指标名称："+indexname+"（"+zhibiaodanwei+"）";
			
			var ChartTableshuoming = "数据说明："+siteTypeName+"指标星期走势"+"<br/>"
					+"时间范围："+stadubiao+(endtubiao==null?'':"~"+endtubiao)+"<br/>"
					+"场所名称："+siteN+"<br/>"
					+"指标名称："+indexname+"（"+zhibiaodanwei+"）";
			$("#ChartTableshuoming").html(ChartTableshuoming);
   			var timeType_table = ret.timeType_table;//返回的日周月年
   			var  result = ret.result;//返回数据集
   			var  markLinePrecision = 0;
   			var xsisRe="";//X轴
   			var dateStr=""//数据data
   			var titName="";//表题
   			xsis = ['周一','周二 ','周三','周四','周五','周六','周日'];
			var seriesIndexs = new Array();
			var startEndOfWeeks = new Array();
   			for(var i=0;i<result.length;i++){
	   			var param=result[i];
				var yearWeek = insert_flg(param.yearWeek,".",4)
				var startEndOfWeek = getTiptollTime(yearWeek);
				startEndOfWeeks.push(startEndOfWeek);
	   			titName=titName+"第"+(parseInt(param.weeknum)<10?"0"+param.weeknum:param.weeknum)+"周"+",";
	   			var resultXY=getXY(param,type);
	   			var dataRe=resultXY[0];
				var dataIndexs = resultXY[1];
				seriesIndexs.push(dataIndexs);
	   			dateStr=dateStr+"{name:'第"+(parseInt(param.weeknum)<10?"0"+param.weeknum:param.weeknum)+'周'+"',markLine: {precision:markLinePrecision,data: [{type: 'average',name: '平均值'}]},type:'line',smooth: smoothType,itemStyle:{ normal:{color:'#feab41'}},itemStyle:{normal:{label:{show:"+getShow(xsis)+",position:'top'}}},data:[" +dataRe + "]}"+",";
   			}
   			
   			titName=titName.split(",")
   			data = eval("["+dateStr+"]");
   			
   			var  option = {
//   			tooltip : {
////   				trigger: 'axis'
//   			},
   			tooltip: {
   				trigger: 'axis',
   				backgroundColor: 'rgba(0,0,0,0.7)',
   				position: function(p) {
   					return [p[0] + 10, p[1] - 10];
   				},
//   				formatter: siteName+"<br/>{a}:{b}<br/>"+indexname+":{c}"
				formatter: function(params, ticket, callback) {
					var returnstr = "";
						var time = params[0][1];
							returnstr = "<tr>"+siteName+"<br/>"+time+"</tr>";
						for (var i=0; i<params.length; i++) {
							var a = params[i][0];
							var c = params[i][2];
							c = addKannma(c);
							if (c == '') {
								c = 0;
							}
							returnstr = returnstr +  "<tr><td>"+a+"</td><td>"+"("+startEndOfWeeks[i]+")"+"："+"</td><td style='text-align: right;'>"+c+"</td></tr>";
							
						};
						var table = "<table>"+returnstr+"</table>"
						return table;
   				}
   			},
   			dataZoom: {
   		        show: true,
   		        y:dataZoomY 
   		    },
   		    title : {
 		      text: titContext,
 		      y:'bottom',
 		      x:titleOffens,
 		      textStyle:{
 		        fontSize: 12,
   		        color: '#666',
				fontFamily:'微软雅黑, 兰亭细黑, 宋体',
   		        fontWeight:'normal'
   		    	}		
 		    },
   			legend: {
   					data:titName,
   					y:legendY
   					},
			grid:{
   				x:'7.6%',
   				y:'11%',
   				y2:'27%',
   				borderWidth: gridBorderWidth,
				borderColor:'#EEE'
   			},
		    toolbox: {
		        show : true,
		        feature : {
		            mark : {show: true},
		            magicType : {show: true, type: ['line', 'bar']},
		            restore : {show: true},
		            saveAsImage : {show: true,name:toolboxName}
		        },
		        x:toolboxX,
		        y:toolboxY
		    },
		    calculable : true,
		    xAxis : [
		        {
		        	name : '星期',
		        	boundaryGap: true,//两端空白策略
		        	allowDecimals :true,//使用小数
		            type : 'category',
		            splitLine: {show: xAxisSplitLine,
					lineStyle:{
							 color: ['#EEE'],
							
						}},//不显示竖线
		            splitArea:{
						show:xAxissplitArea,
						areaStyle:{
								color: [
						        'rgba(250,250,250,0.1)',
						        'rgba(200,200,200,0.1)']
							}
					},
		            data : xsis,
		            axisTick:{
						show:true,
						interval:0
					}
		        }
		    ],
		    yAxis : [
		        {
					axisLabel:{
						formatter: function (value) {
		            		if(value > 10000){
		            			return (value/10000)+'万';
		            		}else{
		            			return value + '';
		            		}
						}
					},
		        	splitLine: {
						show: yAxisSplitLine,
						lineStyle:{
							 color: ['#EEE'],
							
						}},//不显示竖线
		        	splitArea:{
						show:yAxissplitArea,
						areaStyle:{
							color: [
					        'rgba(250,250,250,0.1)',
					        'rgba(200,200,200,0.1)']
						}
					},
		        	name : indexname+'('+zhibiaodanwei+')',
		            type : 'value'
		        }
		    ],
		    series : data
		};
   			//改变窗口大小使图标自适应窗口显示
   			window.onresize = function () {
   				myChart.resize();
   			}
   			//加载折线图
   			myChart.setOption(option);
   			//加载表格
   			loadChartTable(xsis,result,type);
   			//加载条形图标  		
   			loadStripeGraph(result,type);
   			hideLoading();
   		},
		error : function(mm, a, b, c, d, e) {
				hideLoading();
				alert("服务器好像开小差了，刷新一下试试吧！");
			}
   		
   	})
}
 
function loadChartTable(xsis,result,type){
	//计算table列宽
	var rowNum = result.length;
	var rowWidth = 0;
	rowWidth = ((100-5.4)/(1+rowNum));
	
	var array=new Array();
	array[1]= "<tr><th class='xykongbai'></th><th class='xyxuhao'>序号</th><th style='width: "+rowWidth+"%;'>星期/周</th>";
	array[2]="<tr><td class='xykongbai'></td><td class='xyxuhao'>1</td><td >"+xsis[0]+"</td>";
	array[3]="<tr><td class='xykongbai'></td><td class='xyxuhao'>2</td><td >"+xsis[1]+"</td>";
	array[4]="<tr><td class='xykongbai'></td><td class='xyxuhao'>3</td><td >"+xsis[2]+"</td>";
	array[5]="<tr><td class='xykongbai'></td><td class='xyxuhao'>4</td><td >"+xsis[3]+"</td>";
	array[6]="<tr><td class='xykongbai'></td><td class='xyxuhao'>5</td><td >"+xsis[4]+"</td>";
	array[7]="<tr><td class='xykongbai'></td><td class='xyxuhao'>6</td><td >"+xsis[5]+"</td>";
	array[8]="<tr><td class='xykongbai'></td><td class='xyxuhao'>7</td><td >"+xsis[6]+"</td>";
	for(var i=0;i<result.length;i++){
		array[1]=array[1]+"<th style='width: "+rowWidth+"%;'>第"+(parseInt(result[i].weeknum)<10?"0"+result[i].weeknum:result[i].weeknum)+"周</th>"
		indexName = getOrderField(type);
		var arr1 = (addKannma(getObjectVlue(result[i].resultList[0],indexName)))==""?"0":(addKannma(getObjectVlue(result[i].resultList[0],indexName)));
		var arr2 = (addKannma(getObjectVlue(result[i].resultList[1],indexName)))==""?"0":(addKannma(getObjectVlue(result[i].resultList[1],indexName)));
		var arr3 = (addKannma(getObjectVlue(result[i].resultList[2],indexName)))==""?"0":(addKannma(getObjectVlue(result[i].resultList[2],indexName)));
		var arr4 = (addKannma(getObjectVlue(result[i].resultList[3],indexName)))==""?"0":(addKannma(getObjectVlue(result[i].resultList[3],indexName)));
		var arr5 = (addKannma(getObjectVlue(result[i].resultList[4],indexName)))==""?"0":(addKannma(getObjectVlue(result[i].resultList[4],indexName)));
		var arr6 = (addKannma(getObjectVlue(result[i].resultList[5],indexName)))==""?"0":(addKannma(getObjectVlue(result[i].resultList[5],indexName)));
		var arr7 = (addKannma(getObjectVlue(result[i].resultList[6],indexName)))==""?"0":(addKannma(getObjectVlue(result[i].resultList[6],indexName)));
		array[2]=array[2]+"<td>"+arr1+"</td>"
		array[3]=array[3]+"<td>"+arr2+"</td>"
		array[4]=array[4]+"<td>"+arr3+"</td>"
		array[5]=array[5]+"<td>"+arr4+"</td>"
		array[6]=array[6]+"<td>"+arr5+"</td>"
		array[7]=array[7]+"<td>"+arr6+"</td>"
		array[8]=array[8]+"<td>"+arr7+"</td>"
		if(i==result.length-1){
			array[1]=array[1]+"<th class='xykongbai'></th></tr>"
			array[2]=array[2]+"<td></td></tr>"
			array[3]=array[3]+"<td></td></tr>"
			array[4]=array[4]+"<td></td></tr>"
			array[5]=array[5]+"<td></td></tr>"
			array[6]=array[6]+"<td></td></tr>"
			array[7]=array[7]+"<td></td></tr>"
			array[8]=array[8]+"<td></td></tr>"
		}
	}	
	var strTr="";
	for(var i=1;i<array.length;i++){
		strTr=strTr+array[i];
	}
	var html="<table  class='indextable xyliebiao widthall' id=\"tableOut\">"+strTr+"</table>";
	$("#hdtable1").val(html);
	$("#ChartTable").html(html);
}
 
 function loadStripeGraph(result,type){
	 
	 	var xsisRe="";//X轴
		var dateStr1=""//工作日数据data
		var dateStr2=""//周末数据data
		var titName="";//表题
		
		
		for(var i=0;i<result.length;i++){
			var gongzuori=0;
			var zhoumo=0;
			
			var param=result[i];
			var resultData = param.resultList;
			var indexNameGraph = getOrderField(type);
			for(var n=0;n<resultData.length;n++){
				if(n<5){
					gongzuori=gongzuori+ parseInt(getObjectVlue(resultData[n],indexNameGraph));
				}else{
					zhoumo=zhoumo+ parseInt(getObjectVlue(resultData[n],indexNameGraph));
				}
			}
			dateStr1=dateStr1+gongzuori+',';
			dateStr2=dateStr2+zhoumo+',';
			xsisRe=xsisRe+"第"+(parseInt(param.weeknum)<10?"0"+param.weeknum:param.weeknum)+'周'+',';
		}
		xsisRe=xsisRe.substring(0,xsisRe.length-1);
		xsis = xsisRe.split(",");
		dateStr1=dateStr1.substring(0,dateStr1.length-1);
		dateStr1 = dateStr1.split(",")
		dateStr2=dateStr2.substring(0,dateStr2.length-1);
		dateStr2 = dateStr2.split(",")
		var markLinePrecision = 0;
		dateStr="{name:'工作日',markLine: {precision:markLinePrecision,data: [{type: 'average',name: '平均值'}]},type:'bar',stack: '总量', barWidth:50,itemStyle:{  normal: {label : {show: true, position: 'insideTop'}}},data:[" +dateStr1 + "]}"+","+"{name:'周末',markLine: {precision:markLinePrecision,data: [{type: 'average',name: '平均值'}]},type:'bar',stack: '总量', barWidth:50,itemStyle:{ normal:{color:'#feab41'}},itemStyle:{ normal: {label : {show: true, position: 'insideTop'}}},data:[" +dateStr2 + "]}"+",";
		
		data = eval("["+dateStr+"]");
		var width = $("#stripegraph").width();
		var height = $("#stripegraph").height();
		var titleOffens = width*7.6/100;
		var dataZoomY = height*(1-19/100);
		var toolboxX = width*81.5/100;
		var legendY = height*4/100;
		var toolboxY = height*4/100;
		var StripeContext="数据说明："+stadubiao+"~"+endtubiao+siteN+"工作日&周末"+indexname+"（"+zhibiaodanwei+"）"+"分布";
		StripeContext="数据说明："+siteTypeName+"指标工作日&周末对比"+"\n"
					+"时间范围："+stadubiao+(endtubiao==null?'':"~"+endtubiao)+"\n"
					+"场所名称："+siteN+"\n"
					+"指标名称："+indexname+"（"+zhibiaodanwei+"）";
			
		var stripegraphshuoming = "数据说明："+siteTypeName+"指标工作日&周末对比"+"<br/>"
				+"时间范围："+stadubiao+(endtubiao==null?'':"~"+endtubiao)+"<br/>"
				+"场所名称："+siteN+"<br/>"
				+"指标名称："+indexname+"（"+zhibiaodanwei+"）";
		
		$("#stripegraphshuoming").html(stripegraphshuoming);
		//获取当前时间
		var date = new Date;
		var today = timeFormat(date);
		//保存图片的名称
		var toolboxName = $("#titles").val()+'-工作日&周末对比'+today;
	 
	 var myChart = echarts.init(document.getElementById("stripegraph"));
	var option = {
				title : {
			      text: StripeContext,
			      y:'bottom',
			      x:titleOffens,
			      textStyle:{
			        fontSize: 12,
	   		        color: '#666',
					fontFamily:'微软雅黑, 兰亭细黑, 宋体',
	   		        fontWeight:'normal'
			    	}		
			    },
			    tooltip: {
	   				trigger: 'axis',
	   				backgroundColor: 'rgba(0,0,0,0.7)',
	   				position: function(p) {
	   					return [p[0] + 10, p[1] - 10];
	   				},
					formatter: function(params, ticket, callback){
						var returnstr = "";
						var time = params[0][1];
							returnstr = "<tr>"+time+"</tr>";
						for (var i=0; i<params.length; i++) {
							var a = params[i][0];
							var c = params[i][2];
							c = addKannma(c);
							if (c == '') {
								c = 0;
							}
							returnstr = returnstr +  "<tr><td>"+a+"："+"</td><td  style='text-align: right;'>"+c+"</td></tr>";
							
						};
						var table = "<table>"+returnstr+"</table>"
						return table;
					}
	   			},
			    grid:{
	   				x:'7.6%',
	   				y:'11%',
	   				y2:'27%',
	   				borderWidth: gridBorderWidth,
				borderColor:'#EEE'
	   			},
			    legend: {
			        data:['工作日', '周末'],
//			        y:legendY
			    },
			    dataZoom: {
	   		        show: true,
	   		        y:dataZoomY 
	   		    },
			    toolbox: {
			        show : true,
			        feature : {
			            mark : {show: true},
			            magicType : {show: true, type: ['line', 'bar','stack', 'tiled']},
			            restore : {show: true},
			            saveAsImage : {show: true,name:toolboxName}
			        },
			        x:toolboxX,
//			        y:toolboxY
			    },
			    calculable : true,
			    xAxis : [
			        {
			        	name : '日期'+'('+'周'+')',
		        		boundaryGap: true,//两端空白策略
		        	 	type : 'category',
		        	 	 splitLine: {show: xAxisSplitLine,
							lineStyle:{
									 color: ['#EEE'],
									
								}},//不显示竖线
				            splitArea:{
								show:xAxissplitArea,
								areaStyle:{
										color: [
								        'rgba(250,250,250,0.1)',
								        'rgba(200,200,200,0.1)']
									}
							},
			            data : xsis
			            
			        }
			    ],
			    yAxis : [
			        {
						axisLabel:{
							formatter: function (value) {
			            		if(value > 10000){
			            			return (value/10000)+'万';
			            		}else{
			            			return value + '';
			            		}
							}
						},
			        	splitLine: {
						show: yAxisSplitLine,
						lineStyle:{
							 color: ['#EEE'],
							
						}},//不显示竖线
			        	splitArea:{
							show:yAxissplitArea,
							areaStyle:{
								color: [
						        'rgba(250,250,250,0.1)',
						        'rgba(200,200,200,0.1)']
							}
						},
			        	name : indexname+'('+zhibiaodanwei+')',
			        	type : 'value'
			        }
			    ],
			    series : data
			};
	 
	//改变窗口大小使图标自适应窗口显示
		window.onresize = function () {
			myChart.resize();
		}
	 myChart.setOption(option);
	 
	 //加载table
	 loadStripeTable(xsis,dateStr1,dateStr2,type);
 }
 
 
 function loadStripeTable(xsis,dateStr1,dateStr2,type){
	 	//计算table列宽
		var rowNum = dateStr1.length;
		var rowWidth = 0;
		rowWidth = ((100-5.4)/(1+rowNum));
	 
	 
		var head="<table  class='indextable xyliebiao widthall' id=\"tableOut1\" >";	
		
		var titlehead="<tr><th class='xykongbai'></th><th class='xyxuhao'>序号</th>"
			var titleTr="<th style='width: "+rowWidth+"%;'>日期类型/周</th>"
			for(var i=0;i<xsis.length;i++){
				titleTr=titleTr+"<th style='width: "+rowWidth+"%;'>"+xsis[i]+"</th>";
			}
		var titlefoot="<th class='xykongbai'></th></tr>"
		
			
		var gongzuorihead="<tr><td class='xykongbai'></td><td class='xyxuhao'>1</td>"
			var gongzuoriTr="<td>工作日</td>"
				for(var i=0;i<dateStr1.length;i++){
					var tempds1 = (addKannma(dateStr1[i]))==""?"0":(addKannma(dateStr1[i]));
					gongzuoriTr=gongzuoriTr+"<td>"+tempds1+"</td>";
				}
		var gongzuorifoot="<td></td></tr>"
				 
		var zhourihead="<tr><td class='xykongbai'></td><td class='xyxuhao'>2</td>"
			var zhouriTr="<td>周末</td>"
				for(var i=0;i<dateStr2.length;i++){
					var tempds2 = (addKannma(dateStr2[i]))==""?"0":(addKannma(dateStr2[i]));
					zhouriTr=zhouriTr+"<td>"+tempds2+"</td>";
				}
		var zhourifoot="<td></td></tr>"
		var foot="</table>"
		var html=head+titlehead+titleTr+titlefoot+gongzuorihead+gongzuoriTr+gongzuorifoot+zhourihead+zhouriTr+zhourifoot+foot;
		$("#hdtable").val(html);
	    $("#stripegraphtable").html(html);

	 
	 
 }
	function fromsubmit(){
		var  siteKey=$('#siteKey').val();
		$('#selectSitekey').val(siteKey);
		$('#siteSelectForm').submit();
	}
	

	